package com.ele.client.util;

import com.google.gwt.user.client.History;

import java.util.HashMap;
import java.util.Map;

public class PathHelper {

    private static final String ID = "id";
    private static final String ACTION = "action";

    public static String getParameter(String param) {
        return getParameters().get(param);
    }

    public static Map<String, String> getParameters() {
        Map<String, String> map = new HashMap<String, String>();

        String[] tokens = History.getToken().split("&");
        for (String token : tokens) {
            String[] s = token.split("=");
            String param = s[0];
            String value = s.length > 1 ? s[1] : null;

            map.put(param, value);
        }

        return map;
    }

    public static Long getId() {
        Long result = null;

        try {
            result = Long.valueOf(getParameter(ID));
        } catch (NumberFormatException ignored) {}

        return result;
    }

    public static String getAction() {
        return getParameter(ACTION);
    }

    public static void setParameter(String param, String value) {
        Map<String, String> parameters = getParameters();
        parameters.put(param, value);

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String v = entry.getValue();
            if (v != null && !v.isEmpty()) {
                sb.append("&").append(entry.getKey()).append("=").append(v);
            }
        }
        sb.replace(0, 1, "");

        History.newItem(sb.toString(), false);
    }

    public static void setId(Long id) {
        setParameter(ID, id == null ? null : String.valueOf(id));
    }

    public static void setAction(String action) {
        setParameter(ACTION, action);
    }
}
